﻿$(function () {
    toastr.options.positionClass = 'toast-bottom-center';
    var vm = new Vue({
        el: '#app',
        data: {
            // 角色与权限
            roomPermission: true, // 能进到本页面，就是true
            roomAddPermission: false,
            roomDeletePermission: false,
            roomEditPermission: false,
            multiDepartmentPermission: false,

            // 主页面
            filterName: '',
            dialogVisible: false, // 创建用户对话框，是否显示
            dialogTitle: '新建诊室',
            actionType:'新建',
            tableData: [],
            formLabelWidth: '80px',
            department: null,   // 当前科室
            treeData: [],
            currentPage: 1,
            totalCount : 0,
            pageSize: 10,
            selectedRows: [],

            room: {
                id:null,
                name: null,
                outerCode: null,
                code:null,
                isActive: null,
                desc:null
            },

            defaultProps: {     // 科室和tree-node对象的映射
                label: 'name',
                children: 'children'
            },

            // 验证规则
            rules: {
                name: [
                    { required: true, message: '请输入名称', trigger: 'blur' }
                ],
                outerCode: [
                    { required: true, message: '请输入编码', trigger: 'blur' }
                ]
            }
        },
        computed: {
            tableShow: function () {
                var vm = this;
                if ((vm.treeData[0] && vm.treeData[0].children.length > 0) || vm.department) {
                    return true;
                }
                return false;
            }
        },
        methods: {
            onOuterCodeChange(val) {
                const vm = this;
                vm.room.code = val;
            },

            // 当前前页改变
            currentPageChange(val) {
                var vm = this;
                vm.currentPage = val;
                vm.loadTableData();
            },

            // 科室用户，每页数量改变
            pageSizeChange(val) {
                var vm = this;
                vm.pageSize = val;
                vm.currentPage = 1;
                vm.loadTableData();
            },

            // 科室选中用户改变
            selectedChange(val) {
                var vm = this;
                vm.selectedRows = val;
            },

            // 加载当前科室下用户
            loadTableData() {
                var vm = this;
                if (vm.multiDepartmentPermission && vm.treeData[0].children.length > 0) { // admin 角色下，有科室
                    vm.department = vm.treeData[0].children[0]; // 默认加载tree中的第一个科室的用户情况
                    vm.loadDepRooms(vm.department.id);
                }
                else if (vm.multiDepartmentPermission && vm.treeData[0].children.length === 0) { // admin角色下，系统中还没创建任何科室
                    // 提示系统还没有任何科
                }
                else if (!vm.multiDepartmentPermission) { // 必然时是科室用户，而且必然是已经登录了某个科室，而且已经加载了科室
                    // 根据登录科室加载用户
                    vm.loadDepRooms(vm.department.id);
                }
            },

            // 加载科室设备类型列表
            loadDepRooms(id) {
                var vm = this;
                abp.ajax({
                    type: 'GET',
                    url: `/api/rooms/get-depart-rooms?depId=${vm.department.id}&filterName=${vm.filterName}&page=${vm.currentPage}&pageSize=${vm.pageSize}`
                }).then(res => {
                    if (res.code === 0) {
                        vm.tableData = res.data.rooms;
                        vm.deproomTotal = res.data.totalCount;
                    }
                });
            },

            loadRoom(id) {
                var vm = this;
                return new Promise(resolve => {
                    abp.ajax({
                        type: 'get',
                        url: `/api/rooms/get?id=${id}`
                    }).then(res => {
                        if (res.code === 0) {
                            vm.room = res.data;
                            resolve();
                        }
                    });
                });
            },

            // 打开创建用户窗口
            showCreate() {
                var vm = this;
                vm.dialogTitle = "新建诊室";
                vm.actionType = "新建";
                vm.room.isActive = true;
                vm.dialogVisible = true;
            },

            // 新建提交
            submitCreate() {
                var vm = this;
                vm.$refs['dialogForm'].validate((vaild) => {
                    if (vaild) {
                        abp.ajax({
                            type: 'post',
                            url: `/api/rooms/submit-create?depId=${vm.department.id}`,
                            data: JSON.stringify(vm.room)
                        }).then(res => {
                            if (res.code == 0) {
                                vm.resetForm();
                                vm.loadDepRooms();
                                abp.notify.success(res.msg);
                            }
                            else {
                                abp.message.error(res.msg);
                            }
                        });
                    }
                });

            },

            // 打开编辑对话框
            showEdit(id) {
                var vm = this;
                vm.dialogTitle = "编辑诊室";
                vm.actionType = "编辑";
                vm.loadRoom(id).then(() => {
                    vm.dialogVisible = true;
                })
            },

            submitEdit() {
                var vm = this;
                vm.$refs['dialogForm'].validate(valid => {
                    if (valid) {
                        abp.ajax({
                            type: 'post',
                            url: `/api/rooms/submit-edit?depId=${vm.department.id}`,
                            data: JSON.stringify(vm.room)
                        }).then(res => {
                            if (res.code === 0) {
                                abp.notify.success(res.msg);
                                vm.resetForm();
                                vm.loadDepRooms();
                            }
                        });
                    }
                });
            },

            save() {
                var vm = this;
                if (vm.actionType === '新建') {
                    vm.submitCreate();
                }
                else {
                    vm.submitEdit();
                }
            },

            // 加载"科室列表(Admin角色)" 和 当前科室(无admin角色，有DepartmentUser权限)
            loadTreeData() {
                var vm = this;
                return new Promise(resolve => {
                    if (vm.multiDepartmentPermission) { // 如果有管理员角色（multiDepartmentPermission只在admin角色中才有）
                        abp.ajax({
                            type: "GET",
                            url: "/api/department-user/get-tree-data"
                        }).then((res) => {
                            if (res.code === 0) {
                                vm.treeData = res.data;
                                resolve();
                            }
                        });
                    }
                    else if (!vm.multiDepartmentPermission) { // 科室用户
                        // 获取当前登录科室
                        abp.ajax({
                            type: "GET",
                            url: "/api/department-user/get-current-user-department"
                        }).then(res => {
                            vm.department = res;
                            resolve();
                        });
                    }
                });
            },

            // 删除诊室
            deleteRoom(id) {
                var vm = this;
                abp.message.confirm("确定要删除诊室？").then(confirmed => {
                    if (confirmed) {
                        abp.ajax({
                            type: 'Get',
                            url: `/api/rooms/delete?id=${id}`
                        }).then(res => {
                            if (res.code === 0) {
                                abp.notify.success(res.msg);
                                vm.loadDepRooms();
                            }
                        });
                    }
                })
            },

            // 删除多个
            deleteMany() {
                var vm = this;
                var idList = vm.selectedRows.map(item => item.id);
                if (vm.selectedRows.length === 0) {
                    abp.notify.error("未选中任何诊室");
                    return;
                }
                else {
                    abp.message.confirm("确定要删除所选诊室？").then(confirmed => {
                        if (confirmed) {
                            abp.ajax({
                                type: 'Post',
                                url: '/api/rooms/delete-many',
                                data: JSON.stringify(idList)
                            }).then(res => {
                                if (res.code === 0) {
                                    abp.notify.success(res.msg);
                                    vm.loadDepRooms();
                                }
                            })
                        }
                    });
                }
            },
            
            // 加载当前用户角色和权限.
            loadPermission() {
                var vm = this;
                return new Promise((resolve, reject) => {
                    if (abp.auth.isGranted('DeviceGroup.Rooms')) { // 科室用设备类型页面权限
                        vm.roomPermission = true;
                        if (abp.auth.isGranted('DeviceGroup.Rooms.Add')) {// 添加现有设备类型
                            vm.roomAddPermission = true;
                        }

                        if (abp.auth.isGranted('DeviceGroup.Rooms.Delete')) { // 移除科室设备类型
                            vm.roomDeletePermission = true;
                        }

                        if (abp.auth.isGranted('DeviceGroup.Rooms.Edit')) { // 创建科室设备类型
                            vm.roomEditPermission = true;
                        }
                    }
                    if (abp.auth.isGranted('OthersGoup.Others.MuMultiDepartment')) {
                        vm.multiDepartmentPermission = true;
                    }
                    resolve();
                });
            },

            // 点击科室
            nodeClicked(node) {
                if (node.icon != 'fa fa-hospital') {
                    var vm = this;
                    vm.department = node;
                    vm.loadDepRooms(vm.department.id);
                }
            },

            // 创建科室用用户，表单重置
            resetForm() {
                var vm = this;
                vm.$refs['dialogForm'].resetFields();
                vm.dialogVisible = false;
                Object.keys(vm.room).forEach(key => {
                    vm.room[key] = null;
                });
            },

            init() {
                var vm = this;
                vm.loadPermission()
                    .then(() => {
                        vm.loadTreeData().then(() => {
                            vm.loadTableData();
                        });
                    });
            }
        },
        created() {
            var vm = this;
            vm.init();
        },
        mounted() {
        }
    });
});